package cn.fastoo.common.service;

import cn.fastoo.common.utils.ORcodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * Created by lowkey on 16/11/26.
 */
@Service
public class QRCodeService {
    @Autowired
    private OSSService ossService;

    public String getQRCodeUploadKey(String content){
        return getQRCodeUploadKey(content,null,null);
    }
    public String getQRCodeUploadKey(String content,String logoUrl){
        if(StringUtils.isBlank(logoUrl)){
            return getQRCodeUploadKey(content);
        }
        return getQRCodeUploadKey(content,logoUrl,null);
    }
    public String getQRCodeUploadKey(String content,String logoUrl,String text){
        String newFileName = UUID.randomUUID() + ".png";
        String qrCodeUrl = "";
        try {
            if(StringUtils.isBlank(logoUrl)){
                qrCodeUrl  = ossService.uploadFile(newFileName, getImageStream(ORcodeUtils.encode(content, 420, 420)));
            }else{
                if(StringUtils.isBlank(text)){
                    qrCodeUrl  = ossService.uploadFile(newFileName, getImageStream(ORcodeUtils.encode(content, 420, 420,logoUrl)));
                }else{
                    qrCodeUrl  = ossService.uploadFile(newFileName, getImageStream(ORcodeUtils.encode(content, 420, 420,logoUrl,text)));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return qrCodeUrl;
    }

    private InputStream getImageStream(BufferedImage bi){
        InputStream is = null;
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream imOut;
        try {
            imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(bi, "png",imOut);
            is= new ByteArrayInputStream(bs.toByteArray());

        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}
